package cn.net.xyan.secrity.acme.handler;

import cn.net.xyan.secrity.acme.CertBot;
import cn.net.xyan.secrity.acme.ChallengeHandler;
import org.shredzone.acme4j.Authorization;
import org.shredzone.acme4j.challenge.Challenge;
import org.shredzone.acme4j.challenge.Dns01Challenge;
import org.shredzone.acme4j.exception.AcmeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SimpleDNSChallengeHandler implements ChallengeHandler {
    private static final Logger LOG = LoggerFactory.getLogger(SimpleDNSChallengeHandler.class);

    /**
     * Prepares a DNS challenge.
     * <p>
     * The verification of this challenge expects a TXT record with a certain content.
     * <p>
     * This example outputs instructions that need to be executed manually. In a
     * production environment, you would rather configure your DNS automatically.
     *
     * @param auth
     *            {@link Authorization} to find the challenge in
     * @return {@link Challenge} to verify
     */
    @Override
    public Challenge handlerChallenge(Authorization auth, CertBot bot) throws AcmeException {
        // Find a single dns-01 challenge
        Dns01Challenge challenge = auth.findChallenge(Dns01Challenge.TYPE);
        if (challenge == null) {
            throw new AcmeException("Found no " + Dns01Challenge.TYPE + " challenge, don't know what to do...");
        }

        // Output the challenge, wait for acknowledge...
        LOG.info("Please create a TXT record:");
        LOG.info("_acme-challenge." + auth.getDomain() + ". IN TXT " + challenge.getDigest());
        LOG.info("If you're ready, dismiss the dialog...");

        StringBuilder message = new StringBuilder();
        message.append("Please create a TXT record:\n\n");
        message.append("_acme-challenge." + auth.getDomain() + ". IN TXT " + challenge.getDigest());
        bot.acceptChallenge(message.toString());

        return challenge;
    }
}
